﻿
using Microsoft.AspNetCore.Mvc.Formatters;
using Microsoft.Net.Http.Headers;
using System.Text;
using WebApi.Models;

namespace WebApi.CustomFormatter;

/// <summary>
/// Custom output formatter for VCard.
/// 字符串类型的 继承 TextOutputFormatter
/// byte 类型的 继承 InputFormatter OutputFormatter
/// </summary>
public class VCardOutputFormatter : TextOutputFormatter
{
    public VCardOutputFormatter()
    {
        SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse( "text/vcard"));
        SupportedEncodings.Add(Encoding.UTF8);
        SupportedEncodings.Add(Encoding.Unicode);
    }

    protected override bool CanWriteType(Type? type)
    {
        return typeof(Contact).IsAssignableFrom(type) ||typeof(IEnumerable<Contact>).IsAssignableFrom(type);
    }


    public override async Task WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding)
    {
     var httpContext = context.HttpContext;
        var serviceProvider = httpContext.RequestServices;
        var logger = serviceProvider.GetRequiredService<ILogger<VCardOutputFormatter>>();
        var buffer = new StringBuilder();
        if (context.Object is IEnumerable<Contact> contacts)
        {
            foreach (var contact in contacts)
            {
                FormattedVCard(buffer,contact, logger);
            }
        }
        else
        {
            FormattedVCard(buffer, (Contact)context.Object!, logger);
        }
        await httpContext.Response.WriteAsync(buffer.ToString(), selectedEncoding);
    }

    private static void FormattedVCard(StringBuilder buffer, Contact contact, ILogger<VCardOutputFormatter> logger)
    {
        buffer.AppendLine("BEGIN:VCARD");
        buffer.AppendLine("VERSION:3.0");
        buffer.AppendLine($"FN:{contact.FullName}");
        buffer.AppendLine($"N:{contact.LastName};{contact.FirstName}");
        buffer.AppendLine($"UID:{contact.Id}");
        buffer.AppendLine("END:VCARD");

        logger.LogInformation("VCard for {Contact} generated", contact.FullName);
    }
}
